package com.gudong.filter.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.gudong.filter.config.InterProperties;
import com.gudong.filter.config.RepeatedlyRequestWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.BufferedReader;
import java.util.Map;

@Slf4j
public class WebInvokeInterceptor implements HandlerInterceptor {
    @Resource
    private InterProperties interProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        //获取请求体里面的参数
        String jsonParam = "";
        if (request instanceof RepeatedlyRequestWrapper requestWrapper) {
            BufferedReader reader = requestWrapper.getReader();
            jsonParam = IoUtil.read(reader);
            log.info("开始请求 => URL[{}],参数类型[json],参数:[{}]", requestURI, jsonParam);
        } else {
            //获取路径参数
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!CollectionUtils.isEmpty(parameterMap)) {
                jsonParam = JSONUtil.toJsonStr(parameterMap);
                log.info("开始请求 => URL[{}],参数类型[path],参数:[{}]", requestURI, jsonParam);
            }
            //get请求路径参数
            if (request.getMethod().equals("GET")) {
                String queryString = request.getQueryString();
                if (queryString != null) {
                    jsonParam = JSONUtil.toJsonStr(parameterMap);
                    log.info("开始请求 => URL[{}],参数类型[query],参数:[{}]", requestURI, jsonParam);
                }
            }
        }

        //判断是否请求登录
        if (!requestURI.equals("/user/user-info/wxLogin")) {
            if (interProperties == null || CollectionUtils.isEmpty(interProperties.getExcludeApis()) || !interProperties.getExcludeApis().contains(requestURI)) {
                String token = request.getHeader("token");
                if (token == null) {
                    response.setStatus(401);
                    return false;
                }
                if (!StpUtil.isLogin()) {
                    response.setStatus(401);
                    throw new RuntimeException("token已失效");
                }
            }

        }
        return true;
    }

}